package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectOne;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.bcrypt.PasswordConfig;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.AdUserLoginDto;
import com.heima.model.user.dtos.UserAuthDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-10-15
 */
@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Autowired
    private PasswordConfig passwordConfig;

    @Override
    public Map<String, Object> login(AdUserLoginDto dto) {
//        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
//            throw new LeadException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
//        }
        //根据用户名查询用户信息
        LambdaQueryWrapper<AdUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AdUser::getName, dto.getName());
        AdUser adUser = getOne(lqw);
        if (adUser == null) {
            log.info("用户名不存在");
            throw new LeadException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //加密后的密码块
        String password = adUser.getPassword();
        //bcrypt的方法验证前端传递的密码块
        boolean matches = passwordConfig.passwordEncoder().matches(dto.getPassword(), password);
        if (!matches) {
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //生成token
        String token = JwtUtils.generateTokenExpireInSeconds(adUser.getId(), 120);
        Map<String, Object> map= new HashMap<>();
        map.put("user", BeanHelper.copyProperties(adUser, AdUserDto.class));
        map.put("token",token );
        return map;
    }
}
